﻿using System;
using System.Configuration;
using System.Data;
using System.IO;
using HiTeachers.Services;
using HiTeachers.Utilities;

namespace HiTeachers.Web
{
    public partial class Contact : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack) return;
            Page.CloseMessage(lblMsg);

            BindingMetaData("Contact");
            var siteConfig = SiteConfigServices.GetByTextKey("Contact");
            if (siteConfig != null) Page.Title = siteConfig.Value;
        }

        protected void BtnSaveClick(object sender, EventArgs e)
        {
            Page.CloseMessage(lblMsg);
            lblMsgCapt.Visible = false;
            if (!Page.IsValid) return;

            captCode.ValidateCaptcha(txtCaptText.Text);
            if (!captCode.UserValidated)
            {
                lblMsgCapt.Visible = true;
                return;
            }

            try
            {
                string tmpPath = Server.MapPath("mailtemplates");
                string mailCntPath = Path.Combine(tmpPath, "MailContents.xml");

                var dataSet = new DataSet();
                dataSet.ReadXml(mailCntPath);
                DataRow[] rows = dataSet.Tables["ContactEmail"].Select();
                string subject = Convert.ToString(rows[0]["Subject"]);

                subject = subject.Replace("$contactName", txtName.Text);
                string adminEmail = ConfigurationManager.AppSettings["smtp.adminEmail"];

                NVelocityBuilder.SetResourcePath(tmpPath);
                string contentMail = NVelocityBuilder.ContactBuilder(Convert.ToString(rows[0]["Content"]), txtName.Text, txtEmail.Text, txtContent.Text);

                EmailSender.SendMail(subject, contentMail, adminEmail);
                Page.DisplayMessage(lblMsg, "Nội dung liên hệ đã được gửi.", MessageType.Success);
                ClearInputFields();
            }
            catch (Exception ex)
            {
                Page.DisplayMessage(lblMsg, "Lổi kết nối! Bạn có thể liên hệ lại sau.", MessageType.Error);
                //throw;
            }
        }

        protected void BtnCancelClick(object sender, EventArgs e)
        {
            ClearInputFields();
        }

        #region Private Methods
        private void ClearInputFields()
        {
            txtName.Text = string.Empty;
            txtEmail.Text = string.Empty;
            txtContent.Text = string.Empty;
            txtCaptText.Text = string.Empty;
        }
        #endregion
    }
}
